#!/usr/bin/env python3
# -*- coding: UTF-8 -*-
# Copyright (C) 2024 leepongmin, Inc. All Rights Reserved 
# @Time    : ${DATE} ${TIME}
# @Author  : ####leepongmin####
# @Email   : ####leepongmin@hotmail.com####
# @File    : ${NAME}.py
# @Software: ${PRODUCT_NAME}

import re
import pandas as pd

# 输入输出文件
input_file = "SZX_renhang_FW_11.1.30.212.log"
output_excel = "parsed_output.xlsx"

# 正则定义
rule_pattern = re.compile(r"rule (\d+)")
name_pattern = re.compile(r"name ([^\n]+)")
source_ip_pattern = re.compile(r"source-ip ([^\n]+)")
destination_ip_pattern = re.compile(r"destination-ip ([^\n]+)")
service_pattern = re.compile(r"service ([^\n]+)")

# 初始化数据结构
rule_data = []
object_groups = {}
current_object_group = None

# 读取和处理内容
with open(input_file, "r", encoding="gbk", errors="ignore") as f:
    lines = f.readlines()
    content = "".join(lines)  # 用于规则提取
    rules = content.split("rule ")[1:]

    # 提取 firewall 规则
    for rule in rules:
        rule = "rule " + rule
        rule_id = rule_pattern.search(rule)
        name = name_pattern.search(rule)
        source_ips = source_ip_pattern.findall(rule)
        destination_ips = destination_ip_pattern.findall(rule)
        services = service_pattern.findall(rule)

        rule_data.append([
            rule_id.group(1) if rule_id else "",
            name.group(1).strip() if name else "",
            ", ".join(ip.strip() for ip in source_ips) if source_ips else "any",
            ", ".join(ip.strip() for ip in destination_ips) if destination_ips else "any",
            ", ".join(service.strip() for service in services) if services else "any"
        ])

    # 提取 object-group 网络定义
    for line in lines:
        line = line.strip()
        if line.startswith("object-group ip address"):
            current_object_group = line.split()[-1]
            if current_object_group not in object_groups:
                object_groups[current_object_group] = set()
        elif "network" in line and current_object_group:
            match = re.search(r"(\d+\.\d+\.\d+\.\d+(?: \d+\.\d+\.\d+\.\d+)?(?:/\d+)?)", line)
            if match:
                object_groups[current_object_group].add(match.group(1))

# 转为 DataFrame
df_rules = pd.DataFrame(rule_data, columns=["Rule ID", "Name", "Source IPs", "Destination IPs", "Services"])
df_objects = pd.DataFrame(
    [[group, ", ".join(sorted(ips))] for group, ips in object_groups.items()],
    columns=["Object Group", "Network Range"]
)

# 保存到 Excel
with pd.ExcelWriter(output_excel, engine="openpyxl") as writer:
    df_rules.to_excel(writer, sheet_name="Firewall Rules", index=False)
    df_objects.to_excel(writer, sheet_name="Object Groups", index=False)

print(f"已成功从 {input_file} 提取规则与对象组数据，保存在 {output_excel}")